<?php
class CustomerController extends AppController
{
    var $uses = array(
        'Country','Contact','ContactGroup','SmsOutbox'
    );

    # Set the layout to use
    var $layout = 'customer_layout';

    public function beforeFilter($param_array = null)
    {
        parent::beforeFilter();
    }


    function index(){
        $this->redirect(array('controller' => 'Dashboard', 'action' => 'index'));
    }


    function contact_groups($type = 'get'){
        $authUser = $this->Auth->user();
        $permissions = $this->action_permission;
        if ($this->request->is('ajax')) {
            $this->autoRender = false;
            $this->autoLayout = false;

            switch ($type) {
                case 'get' :
                    /**  Get posted data */
                    $page = isset($_POST['page']) ? $_POST['page'] : 1;
                    /** The current page */
                    $sortname = isset($_POST['sortname']) ? $_POST['sortname'] : 'id';
                    /** Sort column */
                    $sortorder = isset($_POST['sortorder']) ? $_POST['sortorder'] : 'desc';
                    /** Sort order */
                    $qtype = isset($_POST['qtype']) ? $_POST['qtype'] : '';
                    /** Search column */
                    $search_query = isset($_POST['query']) ? $_POST['query'] : '';
                    /** Search string */
                    $rp = isset($_POST['rp']) ? $_POST['rp'] : 10;
                    $limit = $rp;
                    $start = ($page - 1) * $rp;


                    $condition_array = array(
                        'ContactGroup.user_id' => $authUser['id'],
                        'ContactGroup.deleted' => 'n'
                    );

                    if (!empty($search_query)) {
                        if ($qtype == 'name') {
                            $condition_array["ContactGroup.$qtype LIKE"] = $search_query . '%';
                        }
                        else {
                            $condition_array["ContactGroup.".$qtype] = $search_query ;
                        }
                    }
                    $contain = array('Contact');
                    $data_table = $this->ContactGroup->find('all', array('conditions' => $condition_array, 'contain'=>$contain, 'order' => "ContactGroup.$sortname $sortorder", 'limit' => $start . ',' . $limit, 'recursive' => 1));
                    $data_table_count = $this->ContactGroup->find('count', array('conditions' => $condition_array, 'recursive' => -1));

                    $total_records = $data_table_count;

                    if ($data_table) {
                        $return_arr = array();
                        foreach ($data_table as $obj) {
                            $return_arr[] = array(
                                'id' => $obj['ContactGroup']['id'],
                                'cell' => array(
                                    $obj['ContactGroup']['id'],
                                    $obj['ContactGroup']['name'],
                                    count($obj['Contact'])
                                )
                            );
                        }
                        return json_encode(array('success' => true, 'total' => $total_records, 'page' => $page, 'rows' => $return_arr));
                    }
                    else {
                        return json_encode(array('success' => false, 'total' => $total_records, 'page' => $page, 'rows' => array()));
                    }
                    break;

                case 'save' :
                    $data = $_POST;
                    if ($data['id'] == 0) {//Mew
                        if(!in_array('A',$permissions)){
                            return json_encode(array('code' => 1, 'msg' => 'Access Denied.'));
                        }
                    }
                    else{
                        if(!in_array('E',$permissions)){
                            return json_encode(array('code' => 1, 'msg' => 'Access Denied.'));
                        }
                    }

                    if ($data['id'] > 0) {
                        $data['modified_by'] = $authUser['id'];
                    } else {
                        $data['created_by'] = $authUser['id'];
                    }
                    $data['user_id'] = $authUser['id'];

                    if ($this->ContactGroup->save($this->sanitize($data))) {
                        if($data['id'] > 0){
                            return json_encode(array('code' => 0, 'msg' => 'Data Saved'));
                        }
                        else{ //If new pass back extra data if needed.
                            return json_encode(array('code' => 0, 'msg' => 'Data Saved!', 'id'=>$this->ContactGroup->id));
                        }
                    } else {
                        echo json_encode(array('code' => 1, 'msg' => 'Some errors occurred.'));
                    }
                    break;

                case 'delete':
                    if(!in_array('D',$permissions)){
                        return json_encode(array('code' => 1, 'msg' => 'Access Denied.'));
                    }
                    $response = $this->ContactGroup->deleteContactGroup($this->sanitize($_POST['ids']),$authUser['id']);
                    if($response){
                        return json_encode(array('code' => 0, 'msg' => 'Contact Group deleted.'));
                    }
                    else{
                        return json_encode(array('code' => 1, 'msg' => 'Contact Group cannot be deleted.'));
                    }
                    break;
            }
        }

        $user_id = $authUser['id'];
        $page_title = 'Contact Group';
        $page_summary = 'Manage your contact group';
        $page_icon = 'iconfa-group';
        $this->set(compact('page_title','page_summary','page_icon','permissions','user_id'));

    }


    function contacts($type = 'get'){
        $authUser = $this->Auth->user();
        $permissions = $this->action_permission;
        if ($this->request->is('ajax')) {
            $this->autoRender = false;
            $this->autoLayout = false;

            switch ($type) {
                case 'get' :
                    /**  Get posted data */
                    $page = isset($_POST['page']) ? $_POST['page'] : 1;
                    /** The current page */
                    $sortname = isset($_POST['sortname']) ? $_POST['sortname'] : 'id';
                    /** Sort column */
                    $sortorder = isset($_POST['sortorder']) ? $_POST['sortorder'] : 'desc';
                    /** Sort order */
                    $qtype = isset($_POST['qtype']) ? $_POST['qtype'] : '';
                    /** Search column */
                    $search_query = isset($_POST['query']) ? $_POST['query'] : '';
                    /** Search string */
                    /** @var Filters  */
                    $filter_c_group =   isset($_POST['filter_c_group']) ? $_POST['filter_c_group'] : -1 ;

                    $rp = isset($_POST['rp']) ? $_POST['rp'] : 10;
                    $limit = $rp;
                    $start = ($page - 1) * $rp;


                    $condition_array = array(
                        'Contact.user_id' => $authUser['id'],
                        'Contact.deleted' => 'n'
                    );
                    if($filter_c_group != -1){
                        $condition_array["Contact.contact_group_id"] = $filter_c_group ;
                    }
                    if (!empty($search_query)) {
                        if ($qtype == 'fname' || $qtype == 'lname') {
                            $condition_array["Contact.$qtype LIKE"] = $search_query . '%';
                        }
                        else {
                            $condition_array["Contact.".$qtype] = $search_query ;
                        }
                    }
                    $contain = array('ContactGroup'=>array('fields'=>array('ContactGroup.id','ContactGroup.name')));
                    $data_table = $this->Contact->find('all', array('conditions' => $condition_array, 'contain'=>$contain, 'order' => "Contact.$sortname $sortorder", 'limit' => $start . ',' . $limit, 'recursive' => 1));
                    $data_table_count = $this->Contact->find('count', array('conditions' => $condition_array, 'recursive' => -1));

                    $total_records = $data_table_count;

                    if ($data_table) {
                        $return_arr = array();
                        foreach ($data_table as $obj) {
                            if($obj['Contact']['contact_group_id'] == 0){
                                $group_name = 'No Group';
                            }
                            else{
                                $group_name = $obj['ContactGroup']['name'];
                            }
                            $return_arr[] = array(
                                'id' => $obj['Contact']['id'],
                                'cell' => array(
                                    $obj['Contact']['id'],
                                    $obj['Contact']['title'],
                                    $obj['Contact']['fname'],
                                    $obj['Contact']['lname'],
                                    $obj['Contact']['country_code'],
                                    $obj['Contact']['phone_number'],
                                    $group_name
                                )
                            );
                        }
                        return json_encode(array('success' => true, 'total' => $total_records, 'page' => $page, 'rows' => $return_arr));
                    }
                    else {
                        return json_encode(array('success' => false, 'total' => $total_records, 'page' => $page, 'rows' => array()));
                    }
                    break;

                case 'save' :
                    $data = $_POST;
                    if ($data['id'] == 0) {//Mew
                        if(!in_array('A',$permissions)){
                            return json_encode(array('code' => 1, 'msg' => 'Access Denied.'));
                        }
                    }
                    else{
                        if(!in_array('E',$permissions)){
                            return json_encode(array('code' => 1, 'msg' => 'Access Denied.'));
                        }
                    }

                    if ($data['id'] > 0) {
                        $data['modified_by'] = $authUser['id'];
                    } else {
                        $data['created_by'] = $authUser['id'];
                    }
                    $data['user_id'] = $authUser['id'];

                    if ($this->Contact->save($this->sanitize($data))) {
                        if($data['id'] > 0){
                            return json_encode(array('code' => 0, 'msg' => 'Data Saved'));
                        }
                        else{ //If new pass back extra data if needed.
                            return json_encode(array('code' => 0, 'msg' => 'Data Saved!', 'id'=>$this->Contact->id));
                        }
                    } else {
                        echo json_encode(array('code' => 1, 'msg' => 'Some errors occurred.'));
                    }
                    break;

                case 'delete':
                    if(!in_array('D',$permissions)){
                        return json_encode(array('code' => 1, 'msg' => 'Access Denied.'));
                    }
                    $response = $this->Contact->deleteContacts($this->sanitize($_POST['ids']),$authUser['id']);
                    if($response){
                        return json_encode(array('code' => 0, 'msg' => 'Contact deleted.'));
                    }
                    else{
                        return json_encode(array('code' => 1, 'msg' => 'Contact cannot be deleted.'));
                    }
                    break;

                case 'assign':
                    if(!in_array('E',$permissions)){
                        return json_encode(array('code' => 1, 'msg' => 'Access Denied.'));
                    }

                    $data = json_decode($_POST['data'], true);

                    $contact_ids = $data['contact_ids'];
                    $group_id = $data['group_id'];

                    $response = $this->Contact->assignGroup($contact_ids,$group_id,$authUser['id']);
                    if($response){
                        return json_encode(array('code' => 0, 'msg' => 'Contacts assign to group.'));
                    }
                    else{
                        return json_encode(array('code' => 1, 'msg' => 'Contacts cannot be assign to group.'));
                    }
                    break;
            }
        }

        $c_groups = $this->ContactGroup->getContactGroupOptions($authUser['id']);
        $c_group_opt = array(array('id'=>0,'name'=>'No Group'));
        $c_group_filter = array(array('id'=>-1,'name'=>'All'),array('id'=>0,'name'=>'No Group'));
        foreach($c_groups as $key => $name){
            $c_group_opt[] = array(
                'id'=>$key,
                'name'=>$name
            );
            $c_group_filter[] = array(
                'id'=>$key,
                'name'=>$name
            );
        }
        $user_id = $authUser['id'];
        $page_title = 'Contacts';
        $page_summary = 'Manage your contacts';
        $page_icon = 'iconfa-book';
        $this->set(compact('page_title','page_summary','page_icon','permissions','user_id','c_group_opt','c_group_filter'));

    }



    function contact_uploads(){
        $this->autoRender = false;

        $upload_data = $this->Upload->__attach_files();

        $contact_group_id = isset($_POST['contact_group_id']) ? $_POST['contact_group_id']: 0;

        //Get the file name
        $file_name = '';
        $save_to = '';
        foreach($upload_data['files'] as $key => $file){
            if(isset($file['name']) && !empty($file['name'])){
                $file_name = $file['name'];
                $save_to = $file['save_to'];
                break;
            }
        }
        $full_path = $save_to.'/';

        if($file_name){
            $res = $this->import_contact_from_file($file_name,$full_path,$contact_group_id);
            if(!$res['status']){
                $mesg = $res['mesg'];
                foreach($upload_data['files'] as $key => $file){
                    $upload_data['files'][$key]['error']= $mesg;
                }
            }
        }
        else{
            foreach($upload_data['files'] as $key => $file){
                $upload_data['files'][$key]['error']= 'File was not uploaded.';
            }
        }

        $this->Upload->attachment_fire_response($upload_data);
    }


    function import_contact_from_file($filename,$full_path,$contact_group_id){
        # create folders if it does not exist
        $loggedUser = $this->Auth->user();

        $folder = "files".DIRECTORY_SEPARATOR."user_".$loggedUser['id'].DIRECTORY_SEPARATOR;
        # setup directory pathname
        $folderAbsPath = WWW_ROOT . $folder;
        $folderRelPath = $folder;
        //chmod($folderAbsPath, 0777);
        try {
            $objPHPExcel = PHPExcel_IOFactory::load($folderAbsPath.$filename);
           /* $inputFileType = PHPExcel_IOFactory::identify($folderAbsPath.$filename);
            $objReader = PHPExcel_IOFactory::createReader($inputFileType);
            $objPHPExcel = $objReader->load($folderAbsPath.$filename);*/
        } catch(Exception $e) {
            return array('status'=>false,'mesg'=>$e->getMessage());
        }

        //$contact_group_id = $contact_group_id == false ? 0 : $contact_group_id;
        $save = array();
        foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
            $worksheetTitle     = $worksheet->getTitle();
            $highestRow         = $worksheet->getHighestRow(); // e.g. 10
            $highestColumn      = $worksheet->getHighestColumn(); // e.g 'F'
            $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
            $nrColumns = ord($highestColumn) - 64;

            for ($row =2; $row < ($highestRow + 1); ++$row){
                $title   = $objPHPExcel->getActiveSheet()->getCell("A".$row)->getValue();
                $fname = $objPHPExcel->getActiveSheet()->getCell("B".$row)->getValue();
                $lname = $objPHPExcel->getActiveSheet()->getCell("C".$row)->getValue();
                $country_code = $objPHPExcel->getActiveSheet()->getCell("D".$row)->getValue();
                $fon_number = $objPHPExcel->getActiveSheet()->getCell("E".$row)->getValue();
                if(!empty($fon_number)){
                    $save['Contact'][]=array(
                        'title'=>$title,
                        'fname'=>$fname,
                        'lname'=>$lname,
                        'contact_group_id' => $contact_group_id,
                        'country_code'=>$country_code,
                        'phone_number'=>$fon_number,
                        'user_id' => $loggedUser['id'],
                        'created_by' => $loggedUser['id']
                    );
                }
            }
        }
        # save the data
        $this->Contact->create();
        if ($this->Contact->saveAll($save['Contact'])) {
            return array('status'=>true,'mesg'=>"Contact has been imported to the group!");
        } else {
            return array('status'=>false,'mesg'=>'Cannot save contacts to the group.');
        }
    }


    function export_contacts(){
        $this->autoLayout = false;
        $authUser = $this->Auth->user();
        $group_id = isset($_POST) ? $_POST['export-group-id'] : '-1';
        $contact_ids = isset($_POST) ? explode(',',$_POST['export-contact-ids']) : array();
        $condition_array = array(
            'Contact.user_id' => $authUser['id'],
            'Contact.id' => $contact_ids,
            'Contact.deleted' => 'n'
        );
        if($group_id != '-1'){
            $condition_array["Contact.contact_group_id"] = $group_id ;
        }
        $contain = array('ContactGroup'=>array('fields'=>array('ContactGroup.id','ContactGroup.name')));
        $data_table = $this->Contact->find('all', array(
                'conditions' => $condition_array,
                'contain'=>$contain,
                'recursive' => 1
            )
        );
        $list_data = array();
        if ($data_table) {
            foreach ($data_table as $obj) {
                if($obj['Contact']['contact_group_id'] == 0){
                    $group_name = 'No Group';
                }
                else{
                    $group_name = $obj['ContactGroup']['name'];
                }
                $list_data[] = array(
                    $obj['Contact']['id'],
                    $obj['Contact']['title'],
                    $obj['Contact']['fname'],
                    $obj['Contact']['lname'],
                    $obj['Contact']['country_code'],
                    $obj['Contact']['phone_number'],
                    $group_name
                );
            }
        }
        $list_headers = array('ID','Title','First Name','Last Name','Country Code','Phone Number','Contact Group');

        $message = '';
        $download = false;
        if(!empty($list_data)){
            $download = true;
            $filename ="Contacts Export ";
            $res = $this->convertToExcel($list_headers,$list_data,$filename);
            $objPHPExcel = $res['excel_obj'];
            $filename = $res['filename'];
        }
        else{
            $message = "No Contact Records Found";
        }

        $this->set(compact('objPHPExcel', 'download', 'filename','list_data','list_headers','message'));
    }


}